package com.ceadeal.admin.group.wechat.service;

import com.alibaba.fastjson.JSONObject;
import com.ceadeal.admin.group.wechat.util.HttpClientUtil;
import com.ceadeal.admin.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * TODO
 *
 * @author Westin Yang
 * @date 2017-03-31 20:40:03
 */
@Service
public class CloudMusicService {
    private static Logger log = LoggerFactory.getLogger(CloudMusicService.class);

    /**
     * 描述：抓取外链
     *
     * @param
     * @return
     * @throws
     *
     * @author Westin Yang
     * @date 2017-03-31 20:34:22
     */
    public String grabChain(String url) {
        log.info("抓取外链 => 开始 目标地址:{}", url);
        // 从url中获取songId
        Pattern p = Pattern.compile("(.*)(song\\?id=)(.*?)(&)(.*)");
        Matcher m = p.matcher(url);
        String songId = "";
        if (m.matches()) {
            songId = m.group(3);
        }
        if (StringUtil.isEmpty(songId)) {
            p = Pattern.compile("(.*)(song\\?id=)(.*?)");
            m = p.matcher(url);
            if (m.matches()) {
                songId = m.group(3);
            }
        }
        if (StringUtil.isEmpty(songId)) {
            p = Pattern.compile("(.*)(song/)(.*?)(/)(.*)");
            m = p.matcher(url);
            if (m.matches()) {
                songId = m.group(3);
            }
        }
        if (StringUtil.isEmpty(songId)) {
            p = Pattern.compile("(.*)(song/)(.*?)(\\?)(.*)");
            m = p.matcher(url);
            if (m.matches()) {
                songId = m.group(3);
            }
        }

        log.info("抓取外链 => 解析songId:{}", songId);

        // 开始抓取
        String targetUrl = MessageFormat.format("http://music.163.com/api/song/detail/?id={0}&ids=[{1}]&csrf_token=", songId, songId);

        String responseBody = HttpClientUtil.httpGet(targetUrl);

        log.info("抓取外链 => responseBody:{}", responseBody);

        String result = "";
        try {
            JSONObject root = JSONObject.parseObject(responseBody);
            JSONObject songs0 = root.getJSONArray("songs").getJSONObject(0);
            String mp3Url = songs0.getString("mp3Url");
            String picUrl = songs0.getJSONObject("album").getString("picUrl");
            result = MessageFormat.format("抓取成功\n\n音乐链接: {0}\n\n图片链接: {1}\n\n[提示: 音乐链接可能被微信屏蔽导致无法访问，可以复制链接在其他浏览器打开]", mp3Url, picUrl);
            log.info("抓取外链 => 抓取成功，{}", result);
        } catch (Exception e) {
            result = "抓取失败，目标链接无效";
            log.error(e.getMessage());
        }

        return result;
    }

}
